package com.lw.sbdemo2.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.lw.sbdemo2.common.base.CrudService;
import com.lw.sbdemo2.common.utils.DateUtils;
import com.lw.sbdemo2.common.utils.LwUtil;
import com.lw.sbdemo2.common.utils.ValidUtil;
import com.lw.sbdemo2.common.vo.PageInfo;
import com.lw.sbdemo2.entity.TkExamProductDetail;
import com.lw.sbdemo2.entity.TkUserAnswerExamRecord;
import com.lw.sbdemo2.entity.TkUserErrorExamDetail;
import com.lw.sbdemo2.mapper.TkExamProductDetailMapper;
import com.lw.sbdemo2.mapper.TkUserAnswerExamRecordMapper;
import com.lw.sbdemo2.mapper.TkUserErrorExamDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

/**
 * <p>标题: 试卷商品细表服务 - 业务逻辑层</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 山人行工作室</p>
 *
 * @version: 1.0
 * @author: LinWang
 * @date 2019-4-14
 */
@Slf4j
@Service
public class TkExamProductDetailService extends CrudService<TkExamProductDetail, TkExamProductDetailMapper> {

    @Autowired
    private TkUserErrorExamDetailMapper tkUserErrorExamDetailMapper;

    @Autowired
    private TkUserAnswerExamRecordMapper tkUserAnswerExamRecordMapper;

    @Autowired
    private TkExamProductDetailMapper tkExamProductDetailMapper;

    /**
     * 获取用户分页列表
     *
     * @param query               搜索关键词
     * @param pageInfo            分页实体
     * @param tkExamProductDetail 实体入参
     * @return 用户列表
     */
    public PageInfo<TkExamProductDetail> findListPage(String query, PageInfo pageInfo, TkExamProductDetail tkExamProductDetail) {
        PageHelper.startPage(pageInfo);
        List<TkExamProductDetail> tkExamProductDetaillist = this.dao.findListPage(query, tkExamProductDetail);
        return new PageInfo<>(tkExamProductDetaillist);
    }


    /**
     * 提交学生回答答案
     *
     * @param examId
     * @param userId
     * @param useTime
     * @param resultJson
     * @return
     */
    public void submitAnswer(String examId, String userId, String useTime, String questionNum, String resultJson) {

        List<TkUserErrorExamDetail> userErrorArr = new ArrayList<>();

        Map<String, String> mapTypes = JSON.parseObject(resultJson, new TypeReference<HashMap<String, String>>() {
        });

        if (mapTypes == null) {
            return;
        }

        //获取数据库答题 - 判断是否首次
        TkUserAnswerExamRecord tkUserAnswerExamRecordParam = TkUserAnswerExamRecord.builder()
                .userId(userId).examId(examId).build();
        TkUserAnswerExamRecord tkUserAnswerExamRecordDb = tkUserAnswerExamRecordMapper.get(tkUserAnswerExamRecordParam);

        if (mapTypes.isEmpty()) {

            //学生交白卷，直接插入主细表
            //更新答题记录表
            TkUserAnswerExamRecord tkUserAnswerExamRecord = TkUserAnswerExamRecord.builder()
                    .userId(userId).examId(examId).useTime(useTime).wrongCount(questionNum)
                    .answerScore(BigDecimal.ZERO).endTime(new Date()).build();

            if (tkUserAnswerExamRecordDb != null) {
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstAnswerScore())) {
                    tkUserAnswerExamRecord.setFirstAnswerScore(tkUserAnswerExamRecord.getAnswerScore());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstExactRate())) {
                    tkUserAnswerExamRecord.setFirstExactRate(tkUserAnswerExamRecord.getExactRate());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstEndTime())) {
                    tkUserAnswerExamRecord.setFirstEndTime(tkUserAnswerExamRecord.getEndTime());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstUseTime())) {
                    tkUserAnswerExamRecord.setFirstUseTime(tkUserAnswerExamRecord.getUseTime());
                }
            }

            tkUserAnswerExamRecordMapper.update(tkUserAnswerExamRecord);

            //插入错题表
            TkExamProductDetail tkExamProductDetail = TkExamProductDetail.builder().examId(examId).build();
            List<TkExamProductDetail> tkExamProductDetails = tkExamProductDetailMapper.findList(tkExamProductDetail);
            if (!tkExamProductDetails.isEmpty()) {
                TkUserErrorExamDetail tkUserErrorDelete = TkUserErrorExamDetail.builder().examId(examId).userId(userId).build();
                tkUserErrorExamDetailMapper.deleteExamAll(tkUserErrorDelete);
                for (TkExamProductDetail examProductDetail : tkExamProductDetails) {
                    userErrorArr.add(TkUserErrorExamDetail.builder().examId(examId).userId(userId)
                            .questionId(examProductDetail.getQuestionId()).errorAnswer("").handleFlag("1")
                            .errorType(examProductDetail.getQuestionType()).createdTime(new Date()).build());
                }
                tkUserErrorExamDetailMapper.insertDetailBatch(userErrorArr);
            }
        } else {

            BigDecimal scoreAll = new BigDecimal(BigInteger.ZERO);
            BigDecimal wrongCount = new BigDecimal(BigInteger.ZERO);

            //查找所有题目 - 遍历解析
            TkExamProductDetail tkExamProductDetail = TkExamProductDetail.builder().examId(examId).build();
            List<TkExamProductDetail> tkExamProductDetails = tkExamProductDetailMapper.findList(tkExamProductDetail);

            for (TkExamProductDetail examProductDetail : tkExamProductDetails) {

                String questionId = examProductDetail.getQuestionId();
                TkUserErrorExamDetail tkUserErrorExamDetailTemp = TkUserErrorExamDetail.builder()
                        .userId(userId).createdTime(new Date()).examId(examId).errorType(examProductDetail.getQuestionType()).questionId(questionId).build();

                //判断是否有回答该题
                if (mapTypes.containsKey(questionId)) {
                    String userAnswer = mapTypes.get(questionId);
                    String correctAnswer = examProductDetail.getCorrectAnswer();
                    if (Objects.equals(userAnswer, correctAnswer)) {
                        //有回答答对的青睐
                        scoreAll = scoreAll.add(new BigDecimal(examProductDetail.getQuestionScore()));
                    } else {
                        if (correctAnswer.contains("#") && ValidUtil.isNotEmptyAndNull(userAnswer)) {
                            String[] correctAnswerArr = correctAnswer.split("#");
                            String[] userAnswerArr = userAnswer.split("#");
                            int arrLen = correctAnswerArr.length;
                            int errorLen = userAnswerArr.length;
                            int okNum = 0;
                            for (int i = 0; i < correctAnswerArr.length; i++) {
                                if (i < errorLen) {
                                    if (correctAnswerArr[i].equals(userAnswerArr[i])) {
                                        okNum++;
                                    }
                                }
                            }
                            scoreAll = scoreAll.add(new BigDecimal(
                                    LwUtil.mul(examProductDetail.getQuestionScore(), LwUtil.div(okNum + "", arrLen + "", 1))));
                        }

                        //有回答答错的情况
                        wrongCount = wrongCount.add(new BigDecimal(BigInteger.ONE));
                        tkUserErrorExamDetailTemp.setErrorAnswer(userAnswer);
                        userErrorArr.add(tkUserErrorExamDetailTemp);
                    }
                } else {
                    //没回答的情况
                    wrongCount = wrongCount.add(new BigDecimal(BigInteger.ONE));
                    tkUserErrorExamDetailTemp.setErrorAnswer("");
                    userErrorArr.add(tkUserErrorExamDetailTemp);
                }
            }

            //更新答题记录表
            TkUserAnswerExamRecord tkUserAnswerExamRecord = TkUserAnswerExamRecord.builder()
                    .userId(userId).examId(examId).useTime(useTime).wrongCount(String.valueOf(wrongCount))
                    .answerScore(scoreAll).endTime(new Date()).build();
            if (tkUserAnswerExamRecordDb != null) {
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstAnswerScore())) {
                    tkUserAnswerExamRecord.setFirstAnswerScore(tkUserAnswerExamRecord.getAnswerScore());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstExactRate())) {
                    tkUserAnswerExamRecord.setFirstExactRate(tkUserAnswerExamRecord.getExactRate());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstEndTime())) {
                    tkUserAnswerExamRecord.setFirstEndTime(tkUserAnswerExamRecord.getEndTime());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstUseTime())) {
                    tkUserAnswerExamRecord.setFirstUseTime(tkUserAnswerExamRecord.getUseTime());
                }
            }
            tkUserAnswerExamRecordMapper.update(tkUserAnswerExamRecord);

            //插入错题记录表
            TkUserErrorExamDetail tkUserErrorDelete = TkUserErrorExamDetail.builder().examId(examId).userId(userId).handleFlag("1").build();
            tkUserErrorExamDetailMapper.deleteExamAll(tkUserErrorDelete);
            if (userErrorArr.size() > 0) {
                tkUserErrorExamDetailMapper.insertDetailBatch(userErrorArr);
            }
        }
    }

    /**
     * 提交学生回答答案
     *
     * @param examId
     * @param userId
     * @param resultJson
     * @return
     */
    public void submitAnswerStudy(String examId, String userId, String nowIndex, String prevIndex, String nowNum, String questionNum, String resultJson) {

        List<TkUserErrorExamDetail> userErrorArr = new ArrayList<>();

        Map<String, String> mapTypes = JSON.parseObject(resultJson, new TypeReference<HashMap<String, String>>() {
        });

        if (mapTypes == null) {
            return;
        }

        //计算用时
        TkUserAnswerExamRecord tkUserAnswerExamRecordParam = TkUserAnswerExamRecord.builder()
                .userId(userId).examId(examId).build();
        TkUserAnswerExamRecord tkUserAnswerExamRecordDb = tkUserAnswerExamRecordMapper.get(tkUserAnswerExamRecordParam);
        Date startTime = tkUserAnswerExamRecordDb.getStartTime();
        Date endTime = new Date();
        String useTime = "0";
        try {
            useTime = String.valueOf(DateUtils.between(startTime, endTime, DateUtils.DateType.Seconds));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mapTypes.isEmpty()) {

            //学生交白卷，直接插入主细表
            //更新答题记录表
            TkUserAnswerExamRecord tkUserAnswerExamRecord = TkUserAnswerExamRecord.builder()
                    .userId(userId).examId(examId).useTime(useTime).wrongCount(questionNum).nowIndex("0").exactRate(BigDecimal.ZERO).endTime(endTime).build();
            if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstExactRate())) {
                tkUserAnswerExamRecord.setFirstExactRate(tkUserAnswerExamRecord.getExactRate());
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstEndTime())) {
                    tkUserAnswerExamRecord.setFirstEndTime(tkUserAnswerExamRecord.getEndTime());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstUseTime())) {
                    tkUserAnswerExamRecord.setFirstUseTime(tkUserAnswerExamRecord.getUseTime());
                }
            }
            tkUserAnswerExamRecordMapper.update(tkUserAnswerExamRecord);

            //插入错题表
            TkExamProductDetail tkExamProductDetail = TkExamProductDetail.builder().examId(examId).build();
            List<TkExamProductDetail> tkExamProductDetails = tkExamProductDetailMapper.findList(tkExamProductDetail);
            if (!tkExamProductDetails.isEmpty()) {
                TkUserErrorExamDetail tkUserErrorDelete = TkUserErrorExamDetail.builder().examId(examId).userId(userId).build();
                tkUserErrorExamDetailMapper.deleteExamAll(tkUserErrorDelete);
                for (TkExamProductDetail examProductDetail : tkExamProductDetails) {
                    userErrorArr.add(TkUserErrorExamDetail.builder().examId(examId).userId(userId)
                            .questionId(examProductDetail.getQuestionId()).errorAnswer("").handleFlag("1")
                            .errorType(examProductDetail.getQuestionType()).createdTime(new Date()).build());
                }
                tkUserErrorExamDetailMapper.insertDetailBatch(userErrorArr);
            }
        } else {

            BigDecimal wrongCount = new BigDecimal(BigInteger.ZERO);

            //查找所有题目 - 遍历解析
            TkExamProductDetail tkExamProductDetail = TkExamProductDetail.builder().examId(examId).build();
            List<TkExamProductDetail> tkExamProductDetails = tkExamProductDetailMapper.findList(tkExamProductDetail);

            for (TkExamProductDetail examProductDetail : tkExamProductDetails) {

                String questionId = examProductDetail.getQuestionId();
                TkUserErrorExamDetail tkUserErrorExamDetailTemp = TkUserErrorExamDetail.builder()
                        .userId(userId).createdTime(new Date()).examId(examId).errorType(examProductDetail.getQuestionType()).questionId(questionId).build();

                //判断是否有回答该题
                if (mapTypes.containsKey(questionId)) {
                    String userAnswer = mapTypes.get(questionId);
                    String correctAnswer = examProductDetail.getCorrectAnswer();
                    if (!correctAnswer.contains("&")) {
                        if (!Objects.equals(userAnswer, correctAnswer)) {
                            wrongCount = wrongCount.add(new BigDecimal(BigInteger.ONE));
                            tkUserErrorExamDetailTemp.setErrorAnswer(userAnswer);
                            userErrorArr.add(tkUserErrorExamDetailTemp);
                        }
                    } else {
                        String[] tempArr = correctAnswer.split("&");
                        boolean tempBoo = false;
                        for (String tempStr : tempArr) {
                            if (Objects.equals(userAnswer, tempStr)) {
                                tempBoo = true;
                                break;
                            }
                        }
                        if (!tempBoo) {
                            wrongCount = wrongCount.add(new BigDecimal(BigInteger.ONE));
                            tkUserErrorExamDetailTemp.setErrorAnswer(userAnswer);
                            userErrorArr.add(tkUserErrorExamDetailTemp);
                        }
                    }
                } else {
                    //没回答的情况
                    wrongCount = wrongCount.add(new BigDecimal(BigInteger.ONE));
                    tkUserErrorExamDetailTemp.setErrorAnswer("");
                    userErrorArr.add(tkUserErrorExamDetailTemp);
                }
            }

            //页码处理
            if (ValidUtil.isEmptyOrNull(nowIndex)) {
                nowIndex = "0";
            }

            //获取总题目数，计算错误题目数
            int quAllCount = tkExamProductDetails.size();

            if (ValidUtil.isNotEmptyAndNull(nowNum)) {
                int errorPrevNum = tkUserErrorExamDetailMapper.getErrorNum(examId, userId, Integer.parseInt(nowNum));
                wrongCount = wrongCount.subtract(new BigDecimal(String.valueOf(nowNum))).add(new BigDecimal(String.valueOf(errorPrevNum)));
            }

            //准确率统计
            BigDecimal exactRate = BigDecimal.ZERO;
            String wrongConutStr = String.valueOf(wrongCount);
            String quAllCountStr = String.valueOf(quAllCount);
            exactRate = new BigDecimal(LwUtil.mul(LwUtil.div(LwUtil.sub(quAllCountStr, wrongConutStr), quAllCountStr, 2), "100"));

            //更新答题记录表
            TkUserAnswerExamRecord tkUserAnswerExamRecord = TkUserAnswerExamRecord.builder()
                    .userId(userId).examId(examId).useTime(useTime).wrongCount(wrongConutStr).nowIndex(nowIndex).exactRate(exactRate).endTime(endTime).build();
            if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstExactRate())) {
                tkUserAnswerExamRecord.setFirstExactRate(tkUserAnswerExamRecord.getExactRate());
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstEndTime())) {
                    tkUserAnswerExamRecord.setFirstEndTime(tkUserAnswerExamRecord.getEndTime());
                }
                if (ValidUtil.isEmptyOrNull(tkUserAnswerExamRecordDb.getFirstUseTime())) {
                    tkUserAnswerExamRecord.setFirstUseTime(tkUserAnswerExamRecord.getUseTime());
                }
            }
            tkUserAnswerExamRecordMapper.update(tkUserAnswerExamRecord);

            //插入错题记录表
            TkUserErrorExamDetail tkUserErrorDelete =
                    TkUserErrorExamDetail.builder().examId(examId).userId(userId).build();
            tkUserErrorExamDetailMapper.deleteExamAll(tkUserErrorDelete);
            if (userErrorArr.size() > 0) {
                tkUserErrorExamDetailMapper.insertDetailBatch(userErrorArr);
            }
        }
    }
}
